<template>
  <div class="home-container">
    <Header title="我的文件" show-search @search="handleSearch">
      <template #right>
        <van-icon name="plus" @click="showCreateActions = true" />
      </template>
    </Header>

    <div class="home-content">
      <!-- 面包屑导航 -->
      <div v-if="breadcrumbList.length > 0" class="breadcrumb">
        <div class="breadcrumb-wrapper">
          <span class="breadcrumb-item" @click="navigateToRoot">
            <van-icon name="home-o" />
            首页
          </span>
          <template v-for="(item, index) in breadcrumbList" :key="item.id">
            <van-icon name="arrow" class="breadcrumb-separator" />
            <span
              class="breadcrumb-item"
              :class="{ active: index === breadcrumbList.length - 1 }"
              @click="navigateToFolder(item.id, index)"
            >
              {{ item.name }}
            </span>
          </template>
        </div>
      </div>

      <!-- 存储使用情况 -->
      <div class="storage-info" @click="$router.push('/profile')">
        <div class="storage-text">
          <span>已使用 {{ formatFileSize(usedStorage) }} / {{ formatFileSize(storageQuota) }}</span>
          <span class="usage-percent">{{ usagePercentage }}%</span>
        </div>
        <van-progress
          :percentage="usagePercentage"
          color="#1989fa"
          track-color="#f5f5f5"
          :stroke-width="4"
        />
      </div>

      <!-- 文件列表 -->
      <div class="file-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              v-for="file in fileList"
              :key="file.id"
              class="file-item"
              @click="handleFileClick(file)"
            >
              <div class="file-icon">
                <van-icon
                  :name="getFileIcon(file)"
                  :color="getFileIconColor(file)"
                  size="24"
                />
              </div>
              <div class="file-info">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-meta">
                  <span v-if="!file.isFolder && file.fileSize">{{ formatFileSize(file.fileSize) }}</span>
                  <span>{{ formatTime(file.updateTime) }}</span>
                </div>
              </div>
              <div class="file-actions">
                <van-icon
                  name="more-o"
                  @click.stop="showFileActions(file)"
                />
              </div>
            </div>

            <!-- 空状态 -->
            <EmptyState
              v-if="fileList.length === 0 && !loading"
              image="default"
              description="暂无文件"
            />
          </van-list>
        </van-pull-refresh>
      </div>
    </div>

    <!-- 创建操作面板 -->
    <van-action-sheet
      v-model:show="showCreateActions"
      :actions="createActions"
      @select="handleCreateAction"
      cancel-text="取消"
    />

    <!-- 文件操作面板 -->
    <van-action-sheet
      v-model:show="showFileActionSheet"
      :actions="fileActions"
      @select="handleFileAction"
      cancel-text="取消"
    />

    <!-- 重命名弹窗 -->
    <van-dialog
      v-model:show="showRenameDialog"
      title="重命名"
      show-cancel-button
      @confirm="handleRename"
    >
      <van-field
        v-model="newFileName"
        placeholder="请输入新名称"
        autofocus
      />
    </van-dialog>

    <!-- 新建文件夹弹窗 -->
    <van-dialog
      v-model:show="showCreateFolderDialog"
      title="新建文件夹"
      show-cancel-button
      @confirm="handleCreateFolder"
    >
      <van-field
        v-model="newFolderName"
        placeholder="请输入文件夹名称"
        autofocus
      />
    </van-dialog>

    <!-- 文件上传 -->
    <input
      ref="fileInputRef"
      type="file"
      multiple
      style="display: none"
      @change="handleFileUpload"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { showToast, showConfirmDialog, closeToast } from 'vant'
import Header from '@/components/Header.vue'
import EmptyState from '@/components/EmptyState.vue'
import { useFileStore } from '@/stores/file'
import { useUserStore } from '@/stores/user'
import { useUploadStore } from '@/stores/upload'
import type { FileInfo } from '@/api/file'
import { generateDownloadUrl } from '@/api/file'

const router = useRouter()
const fileStore = useFileStore()
const userStore = useUserStore()
const uploadStore = useUploadStore()

// 使用 storeToRefs 保持响应式
const {
  fileList,
  currentFolderId,
  loading,
  breadcrumbList
} = storeToRefs(fileStore)

const {
  usedStorage,
  storageQuota,
  usagePercentage
} = storeToRefs(userStore)

// 方法不需要响应式
const {
  fetchFileList,
  enterFolder,
  navigateToFolder,
  createNewFolder,
  removeFile,
  renameFileItem,
  formatFileSize,
  formatTime
} = fileStore

// 状态
const refreshing = ref(false)
const finished = ref(false)
const showCreateActions = ref(false)
const showFileActionSheet = ref(false)
const showRenameDialog = ref(false)
const showCreateFolderDialog = ref(false)
const selectedFile = ref<FileInfo | null>(null)
const newFileName = ref('')
const newFolderName = ref('')
const fileInputRef = ref<HTMLInputElement>()

// 操作选项
const createActions = [
  { name: '上传文件', value: 'upload' },
  { name: '新建文件夹', value: 'folder' },
  { name: '上传管理', value: 'upload-manage' }
]

const fileActions = computed(() => [
  { name: '下载', value: 'download' },
  { name: '分享', value: 'share' },
  { name: '重命名', value: 'rename' },
  { name: '移动', value: 'move' },
  { name: '删除', value: 'delete', color: '#ee0a24' }
])

// 方法
const onRefresh = async () => {
  refreshing.value = true
  try {
    await fetchFileList()
  } finally {
    refreshing.value = false
  }
}

const onLoad = async () => {
  // 这里可以实现分页加载
  finished.value = true
}

const navigateToRoot = () => {
  navigateToFolder(0)
}

const handleSearch = (value: string) => {
  // TODO: 实现搜索功能
  console.log('搜索:', value)
}

const handleFileClick = (file: FileInfo) => {
  if (file.isFolder === 1) {
    enterFolder(file)
  } else {
    // 预览文件
    router.push(`/preview/${file.id}`)
  }
}

const showFileActions = (file: FileInfo) => {
  selectedFile.value = file
  showFileActionSheet.value = true
}

const handleCreateAction = (action: any) => {
  showCreateActions.value = false

  switch (action.value) {
    case 'upload':
      fileInputRef.value?.click()
      break
    case 'folder':
      newFolderName.value = ''
      showCreateFolderDialog.value = true
      break
    case 'upload-manage':
      router.push('/upload')
      break
  }
}

const handleFileAction = async (action: any) => {
  showFileActionSheet.value = false

  if (!selectedFile.value) return

  switch (action.value) {
    case 'download':
      handleDownload(selectedFile.value)
      break
    case 'share':
      handleShare(selectedFile.value)
      break
    case 'rename':
      newFileName.value = selectedFile.value.fileName
      showRenameDialog.value = true
      break
    case 'move':
      handleMove(selectedFile.value)
      break
    case 'delete':
      handleDelete(selectedFile.value)
      break
  }
}

const handleDownload = async (file: FileInfo) => {
  try {
    showToast({
      type: 'loading',
      message: '正在生成下载链接...',
      duration: 0
    })

    const downloadInfo = await generateDownloadUrl(file.id)

    closeToast()

    // 创建下载链接
    const link = document.createElement('a')
    link.href = downloadInfo.downloadUrl
    link.download = file.fileName
    link.target = '_blank'

    // 在移动端，直接打开链接让浏览器处理下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    showToast({
      type: 'success',
      message: '开始下载'
    })
  } catch (error: any) {
    closeToast()
    showToast({
      type: 'fail',
      message: error.message || '下载失败'
    })
  }
}

const handleShare = (file: FileInfo) => {
  router.push(`/share/create?fileId=${file.id}`)
}

const handleMove = (file: FileInfo) => {
  router.push(`/move?fileId=${file.id}`)
}

const handleDelete = async (file: FileInfo) => {
  const confirmed = await showConfirmDialog({
    title: '确认删除',
    message: `确定要删除 "${file.fileName}" 吗？`
  })

  if (confirmed) {
    try {
      await removeFile(file.id)
    } catch (error) {
      showToast('删除失败')
    }
  }
}

const handleRename = async () => {
  if (!selectedFile.value || !newFileName.value.trim()) {
    showToast('请输入新名称')
    return
  }

  try {
    await renameFileItem(selectedFile.value.id, newFileName.value.trim())
    showRenameDialog.value = false
  } catch (error) {
    showToast('重命名失败')
  }
}

const handleCreateFolder = async () => {
  if (!newFolderName.value.trim()) {
    showToast('请输入文件夹名称')
    return
  }

  try {
    await createNewFolder(newFolderName.value.trim())
    showCreateFolderDialog.value = false
  } catch (error) {
    showToast('创建文件夹失败')
  }
}

const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (files && files.length > 0) {
    uploadStore.addUploadTasks(files, currentFolderId.value)
    showToast({
      type: 'success',
      message: `已添加 ${files.length} 个文件到上传队列`
    })
  }

  // 清空input
  target.value = ''
}

const getFileIcon = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return 'folder-o'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'photo-o'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return 'video-o'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return 'music-o'
    case 'pdf':
      return 'description'
    case 'doc':
    case 'docx':
      return 'description'
    case 'xls':
    case 'xlsx':
      return 'description'
    case 'ppt':
    case 'pptx':
      return 'description'
    case 'txt':
      return 'notes-o'
    case 'zip':
    case 'rar':
    case '7z':
      return 'bag-o'
    default:
      return 'description'
  }
}

const getFileIconColor = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return '#1989fa'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return '#ff976a'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return '#ff976a'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return '#07c160'
    case 'pdf':
      return '#ee0a24'
    case 'doc':
    case 'docx':
      return '#1989fa'
    case 'xls':
    case 'xlsx':
      return '#07c160'
    case 'ppt':
    case 'pptx':
      return '#ff976a'
    default:
      return '#969799'
  }
}

onMounted(async () => {
  try {
    // 如果用户未登录，跳转到登录页
    if (!userStore.isLoggedIn) {
      router.replace('/login')
      return
    }

    await fetchFileList()

    // 如果用户信息不存在，刷新用户信息
    if (!userStore.userInfo) {
      await userStore.refreshUserInfo()
    }
  } catch (error: any) {
    // 如果是401错误，可能是token过期
    if (error.response?.status === 401) {
      userStore.clearUserInfo()
      router.replace('/login')
      return
    }

    showToast({
      type: 'fail',
      message: '数据加载失败'
    })
  }
})
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.home-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.breadcrumb {
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #ebedf0;
}

.breadcrumb-wrapper {
  display: flex;
  align-items: center;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.breadcrumb-wrapper::-webkit-scrollbar {
  display: none;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  color: #1989fa;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.breadcrumb-item:hover {
  background-color: #f5f5f5;
}

.breadcrumb-item.active {
  color: #323233;
  cursor: default;
}

.breadcrumb-item.active:hover {
  background-color: transparent;
}

.breadcrumb-separator {
  margin: 0 4px;
  color: #969799;
  font-size: 12px;
}

.storage-info {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #ebedf0;
  cursor: pointer;
}

.storage-text {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #646566;
}

.usage-percent {
  color: #1989fa;
  font-weight: 500;
}

.file-list {
  flex: 1;
  overflow: hidden;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.file-item:active {
  background-color: #f8f8f8;
}

.file-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 16px;
  color: #323233;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #969799;
  display: flex;
  gap: 8px;
}

.file-actions {
  margin-left: 12px;
  color: #969799;
  cursor: pointer;
}


:deep(.van-progress__portion) {
  border-radius: 2px;
}

:deep(.van-dialog__content) {
  padding: 16px;
}

</style>
